//
//  divideLineView.swift
//  LeDian
//
//  Created by 三秒文化 on 16/3/21.
//  Copyright © 2016年 51ledian. All rights reserved.
//

import UIKit
//import Alamofire
//import QuartzCore
//import SDWebImage
import SnapKit


//MARK: - UIBUTTPN
extension UIButton{
    
    /** button 设置 */
    class func setDetailsBtn(btnTitle:String?,picName:String?,btnBackColor:UIColor?,titleColor:UIColor?) ->UIButton?{
        
        let btn = UIButton(frame: CGRectZero)
        btn.setTitle(btnTitle, forState: UIControlState.Normal)
        if btnTitle != nil {
            btn.setTitle(btnTitle, forState: UIControlState.Normal)
        }
        if picName != nil{
            btn.setImage(UIImage(named: picName!), forState: UIControlState.Normal)
            btn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        }
        if btnBackColor != nil {
            btn.backgroundColor = btnBackColor
            btn.setBackgroundImage(UIImage.setImageWithColor(UIColor.lightGrayColor()), forState: UIControlState.Highlighted)
        }
        if titleColor != nil {
            
            btn.setTitleColor(titleColor, forState: UIControlState.Normal)
            btn.setTitleColor(LDFontColor.Black, forState: UIControlState.Highlighted)
            
        } else {
            btn.setTitleColor(LDFontColor.DeepGray, forState: UIControlState.Normal)
        }
        
        btn.layer.cornerRadius = 4
        btn.layer.masksToBounds = true
        btn.titleLabel?.font = LDFont.Font14
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
        btn.sizeToFit()
        
        return btn
    }
    
    
    /** 距离button */
    class func setDistanceBtn() -> UIButton {
        let btn = UIButton.setDetailsBtn("...km", picName: "address.png", btnBackColor: LDGolbalColor.White, titleColor: nil)!
        btn.titleLabel?.textAlignment = NSTextAlignment.Right
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Right
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
        btn.userInteractionEnabled = false
        return btn
    }
    
    /** 城市button */
    class func setLoactionBtn() -> UIButton {
        let btn = UIButton.setDetailsBtn("城市", picName: "工作地址.png", btnBackColor: LDGolbalColor.White, titleColor: nil)!
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
        btn.titleLabel?.font = LDFont.Font13
        btn.userInteractionEnabled = false
        return btn
    }
    /** 经验button */
    class func setExperienceBtn() -> UIButton {
        let btn = UIButton.setDetailsBtn("经验", picName: "工作经验.png", btnBackColor: LDGolbalColor.White, titleColor: nil)!
        btn.titleLabel?.textAlignment = NSTextAlignment.Left
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
        btn.titleLabel?.font = LDFont.Font13
        btn.userInteractionEnabled = false
        return btn
        
    }
    /** 学历button */
    class func setEduBtn() -> UIButton {
        let btn = UIButton.setDetailsBtn("学历", picName: "教育经历", btnBackColor: LDGolbalColor.White, titleColor: LDFontColor.DeepGray)!
        btn.titleLabel?.textAlignment = NSTextAlignment.Left
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0)
        btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
        btn.titleLabel?.font = LDFont.Font13
        btn.userInteractionEnabled = false
        return btn
    }
    
    class func setListBtn(img:String,title:String?) -> UIButton {
        let btn = UIButton.setDetailsBtn(title, picName: img, btnBackColor: LDGolbalColor.White, titleColor: LDFontColor.DeepGray)!
        btn.titleLabel?.textAlignment = NSTextAlignment.Left
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0)
        btn.titleLabel?.font = LDFont.Font15
        return btn
    }
    //bottom 按钮
    class func setBottomListBtn(img:String,title:String?,margin:CGFloat) -> UIButton {
        let btn = UIButton.setDetailsBtn(title, picName: img, btnBackColor: LDGolbalColor.White, titleColor: LDFontColor.DeepGray)!
        btn.titleLabel?.textAlignment = NSTextAlignment.Center
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, margin, 0, 0)
        btn.titleLabel?.adjustsFontSizeToFitWidth = true
        return btn
    }
    
    //
    class func setDetailsGoundBtn(radius:CGFloat?,img:String) -> UIButton {
        let btn = UIButton.init(type: UIButtonType.Custom)
        
        btn.setBackgroundImage(UIImage.init(named: img), forState: UIControlState.Normal)
        if radius != nil {
            btn.layer.cornerRadius = radius!
        }
        btn.layer.masksToBounds = true
        
        return btn
    }
    /** 图片左右调换*/
    class func setButtonImageToRight(button:UIButton) -> UIButton {
        

        let title = button.titleLabel?.text
        let str = NSString.init(string: title!)
        
        let size = CGSizeMake(200, button.frame.height)
        
        let font = button.titleLabel?.font
        
        let rectLab = str.boundingRectWithSize(size, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName:font!], context: nil)
        let rectImg = button.imageView?.bounds
        
        let labwidth = rectLab.width + 10
        let imageWidth = rectImg?.width ?? 0 //+ 10
        
        print(button.frame)
        button.imageEdgeInsets = UIEdgeInsetsMake(0, labwidth, 0, -labwidth)
        button.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth)
        
        return button
    }
}
//MARK: - UILABEL
extension UILabel {
    /** lab 设置 */
    class func setDetailsLab(labName:String?,fontSize:CGFloat,titleColor:UIColor,Alignment:NSTextAlignment?) ->UILabel{
        let lab = UILabel(frame: CGRectZero)
        
        if labName == nil {
            lab.text = ""
        } else {
            lab.text = labName
        }
        if Alignment != nil {
            lab.textAlignment = Alignment!
        }
        if IPHONE6UP {
            lab.font = UIFont.systemFontOfSize(fontSize)
        }else {
            lab.font = UIFont.systemFontOfSize(fontSize - 2)
        }
        
        lab.textColor = titleColor
        lab.lineBreakMode = NSLineBreakMode.ByTruncatingMiddle
        lab.adjustsFontSizeToFitWidth = false
        lab.numberOfLines = 0
        return lab
    }
    
    /** big Titlelab 设置 */
    class func setHeadTitleLab(title:String) -> UILabel{
        let lab = UILabel.setDetailsLab(title, fontSize: 16, titleColor: LDFontColor.Green,Alignment:nil)
        lab.textAlignment = NSTextAlignment.Left
        return lab
    }
    
    /** big Titlelab 设置 */
    class func setDetailsCountJobLabs(radious:CGFloat,color:UIColor) -> UILabel{
        
        let lab = UILabel.setDetailsLab("共..个职位", fontSize: 10, titleColor: LDFontColor.DeepGray,Alignment:nil)
        lab.textAlignment = NSTextAlignment.Center
        
        lab.layer.cornerRadius = radious
//        lab?.layer.masksToBounds = true

        lab.layer.borderColor = color.CGColor
        lab.layer.borderWidth = 1
        lab.textColor = color
//        lab?.backgroundColor = UIColor.clearColor()
        return lab
    }
    
    /** 生成多个标签栏 */
    class func setMoreSameLabs(view:UIView,SameLabTag:Int,labsCount:() ->Int){
        
        let count = labsCount()
        
        for i in 0..<count {
            
            let jobSameLabs = UILabel.init()
            jobSameLabs.tag = i+SameLabTag
            
            jobSameLabs.backgroundColor = LDGolbalColor.White
            jobSameLabs.textColor = LDFontColor.Green
            jobSameLabs.textAlignment = NSTextAlignment.Center
            jobSameLabs.font = LDFont.Font12
            jobSameLabs.adjustsFontSizeToFitWidth = false
            
            jobSameLabs.layer.cornerRadius = 3
            jobSameLabs.layer.borderWidth = 1
            jobSameLabs.layer.borderColor = LDFontColor.Green.CGColor
            
            view.addSubview(jobSameLabs)
            jobSameLabs.hidden = true
        }
    }
    
    /** - 多个便签frame */
    class func setupLabFrame(stringOfBtnArr:NSArray,SameLabTag:Int,textSize:CGSize,font:UIFont,target:AnyObject,labMargin:(Origin_X:CGFloat,Origin_Y:CGFloat,Margin_X:CGFloat,Margin_Y:CGFloat,LabH:CGFloat)){
        
        let margin_x:CGFloat = labMargin.Margin_X//Margin_V*2//第一行间距多15
        let margin_y = labMargin.Margin_Y //Margin_V*2//每行间距
        
        var btnx:CGFloat = labMargin.Origin_X//Margin_V*5
        var btny:CGFloat = margin_y + labMargin.Origin_Y
        
        let btnH:CGFloat = labMargin.LabH
       
        for i in 0 ..< stringOfBtnArr.count {
            
            let btn = target.viewWithTag(i+SameLabTag) as! UILabel
            
            btn.hidden = false
            
            var labtext = String()
            
            if stringOfBtnArr[i] as! NSObject == NSNull.init() {
                labtext = "NULL"
                btn.text = labtext
            } else {
                labtext = stringOfBtnArr[i] as! String
            }
            btn.text = labtext as String
            let rect = labtext.boundingRectWithSize(textSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:font], context: nil)
            
            let width = rect.width + 20
        
            btn.frame = CGRectMake(btnx, btny, width, btnH)
            btnx = btnx + width + margin_x
            
            if (i+1) % 3 == 0 {
                
                btnx = labMargin.Origin_X//Margin_V*5
                btny = btny + btnH + margin_y
            }
        }
    }
    
    class func getCellSampleLableH(count:Int,labH:CGFloat,LabMargin_V:CGFloat) ->CGFloat {
        let margin = LabMargin_V
        var sampleH:CGFloat = 0
        //只计算4行内的高度
        if count == 0 {
            sampleH = 0
        } else if count < 4 {
            sampleH = labH
        } else if count < 7 {
            sampleH = labH*2 + margin
        } else if count < 10 {
            sampleH = labH*3 + margin*2
        } else {
            sampleH = labH*4 + margin*3
        }
        return sampleH
    }
    
    
    //根据数组生成标签
    class func creatLabsFromArrTags(tagsArr:[String],labsTag:Int,labH:CGFloat,font:UIFont,toView:UIView,originX:CGFloat, originY:CGFloat,marginX:CGFloat,marginY:CGFloat) {
        
        let margin_x = marginX
        let margin_y = marginY
        
        var labX:CGFloat = originX
        var labY:CGFloat = marginY + originY
        
        var totalW:CGFloat = marginX
        
        for i in 0 ..< tagsArr.count {
            
            let lab = UILabel.setDetailsLab("标签", fontSize: 12, titleColor: LDFontColor.Green, Alignment: .Center)
            lab.tag = labsTag + i
            
            let labtext = tagsArr[i]
            lab.text = labtext
            
            lab.layer.borderWidth = 0.5
            lab.layer.borderColor = LDFontColor.Green.CGColor
            lab.layer.cornerRadius = 2.5
            
            let rect = labtext.boundingRectWithSize(CGSizeMake(200, labH-10), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:font], context: nil)
            
            let labW = rect.width + 10
            
            totalW += labW + LDMargin_H*2
            
            if totalW > (LDFrame.ScreenWidth - originX*2) {
                
                totalW = Margin_H*4 + labW
                labX = originX
                labY = labY + labH + margin_y
            }
            
            lab.frame = CGRectMake(labX, labY, labW, labH)
            labX = labX + labW + margin_x
            toView.addSubview(lab)
        }
        
//        let allH = labY + labH + margin_y
    }
    //根据labsArr得到数组高度
    class func getLabsAllHight(tagsArr:[String],labH:CGFloat,font:UIFont,originX:CGFloat, marginX:CGFloat,marginY:CGFloat) ->CGFloat{
        
        
        
        let margin_x = marginX
        let margin_y = marginY
        
        var labX:CGFloat = marginX
        var labY:CGFloat = marginY
        
        var totalW:CGFloat = marginX
        
        for i in 0 ..< tagsArr.count {
            
            let labtext = tagsArr[i]

            let rect = labtext.boundingRectWithSize(CGSizeMake(200, labH-10), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:font], context: nil)
            
            let labW = rect.width + 10
            
            totalW += labW + LDMargin_H*2
            
            if totalW > (LDFrame.ScreenWidth - originX*2) {
                totalW = Margin_H*4 + labW
                labX = margin_x
                labY = labY + labH + margin_y
            }
            
            labX = labX + labW + LDMargin_H*2
        }
        
        let allH = labY + labH + margin_y
        return allH
        
    }
    
    
    //计算lable的frame
    class func getLabRectFromString(font:UIFont,size:CGSize?,str:String) ->CGFloat {
        if size != nil {
            let rect = str.boundingRectWithSize(size!, options: [.UsesLineFragmentOrigin], attributes: [NSFontAttributeName:font], context: nil)
            return rect.size.height
        } else {
            return 0
        }
    }
    
}
//MARK: UITEXTFIELD
extension UITextField {
    
    class func setTextFileldText(title:String,placeHold:String) ->baseTextFiled{
        let field = baseTextFiled()
        field.backgroundColor = LDGolbalColor.White
//        field.borderStyle = UITextBorderStyle.Line
        field.placeholder = placeHold
        
        field.setValue(LDFont.Font14, forKeyPath: "_placeholderLabel.font")
        field.setValue(UIViewContentMode.Center.rawValue, forKeyPath: "_placeholderLabel.contentMode")
//        field.setValue(<#T##value: AnyObject?##AnyObject?#>, forKeyPath: _placeholderLabel.contentMode)
        field.secureTextEntry = true
    
        field.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
        let lab = UILabel.setDetailsLab(title, fontSize: 16, titleColor: LDFontColor.Black, Alignment: .Left)
    
        field.leftView = lab
        field.leftViewMode = UITextFieldViewMode.Always
        return field
    }
}
//MARK: - UIIMAGEVIEW
extension UIImageView {
    
    class func setImageView(radius:CGFloat) -> UIImageView{
        
        let imageView = setdefalutimg { () -> (CGFloat) in
            return radius
        }
        return imageView
    }
    
    
    class func setdefalutimg(closure:()->(CGFloat)) -> UIImageView {
        let imageView = UIImageView.init()
        let radius = closure()
        
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.layer.cornerRadius = radius
        imageView.layer.borderColor = UIColor.whiteColor().CGColor
        imageView.layer.borderWidth = 1
        
        imageView.layer.masksToBounds = true
        
        return imageView
    }
    
    class func setDefaultGoundImg(img:String,radius:CGFloat?) -> UIImageView {
        
        
        let imageView = setdefalutimg { () -> (CGFloat) in
            return radius == nil ? 0:radius!
        }
        
        imageView.image = UIImage.init(named: img)
        return imageView
    }
    // MARK: - 分割虚线 计算水平
    /** 水平 */
    class func setupDivideLine_H(lineWidth:CGFloat) ->UIImageView {
        
    
        let beginPoint: CGPoint = CGPointZero
        let endPoint: CGPoint = CGPoint.init(x: lineWidth, y: 0)
        
        let imageView1 = UIImageView.init(frame:CGRectMake(0, 0, lineWidth, 2))
        
        UIGraphicsBeginImageContext(imageView1.frame.size);   //开始画线
        imageView1.image?.drawInRect(CGRectMake(0, 0, imageView1.frame.size.width, imageView1.frame.size.height), blendMode: CGBlendMode.HardLight, alpha: 1)
        
        let lengths: [CGFloat] = [3.0, 3.0]
        let lineContext = UIGraphicsGetCurrentContext()
        
        CGContextSetStrokeColorWithColor(lineContext, UIColor.grayColor().CGColor)
        
        CGContextSetLineDash(lineContext, 0, lengths, 2);  //画虚线

        CGContextMoveToPoint(lineContext, beginPoint.x, beginPoint.y)
        CGContextAddLineToPoint(lineContext, endPoint.x, endPoint.y)
        
        CGContextStrokePath(lineContext);
        
        imageView1.image = UIGraphicsGetImageFromCurrentImageContext()
        return imageView1
    }
    /** 竖直 */
    class func setupDivideLine_V(lineHeight:CGFloat) ->UIImageView {
        
        
        let beginPoint: CGPoint = CGPointZero
        let endPoint: CGPoint = CGPoint.init(x: 0, y: lineHeight)
        
        let imageView = UIImageView.init(frame:CGRectMake(0, 0, 2, lineHeight))
        
        UIGraphicsBeginImageContext(imageView.frame.size);   //开始画线
        imageView.image?.drawInRect(CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height), blendMode: CGBlendMode.HardLight, alpha: 1)
        
        let lengths: [CGFloat] = [3.0, 3.0]
        let lineContext = UIGraphicsGetCurrentContext()
        
        CGContextSetStrokeColorWithColor(lineContext, UIColor.grayColor().CGColor)
        
        CGContextSetLineDash(lineContext, 0, lengths, 2);  //画虚线
        
        CGContextMoveToPoint(lineContext, beginPoint.x, beginPoint.y)
        CGContextAddLineToPoint(lineContext, endPoint.x, endPoint.y)
        
        CGContextStrokePath(lineContext);
        
        imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        return imageView
    }
}
//MARK: - UIIMAGE
extension UIImage {
    
    /** 原始图片 */
    class func setOrginImage(name:String) -> UIImage {
        var image = UIImage.init(named: name)
        
        image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) ?? UIImage()
        return image!
    }
    
    /** 通过颜色生成图片 */
    class func setImageWithColor(color:UIColor) -> UIImage {
        let rect = CGRectMake(0, 0, 100, 100)
        UIGraphicsBeginImageContext(rect.size)
        //获取上下文
        let context = UIGraphicsGetCurrentContext()
        //填充颜色
        CGContextSetFillColorWithColor(context,color.CGColor)
        CGContextFillRect(context, rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
    
    class func setImageWithColor(color:UIColor,frame:CGRect) -> UIImage {
        let rect = frame//CGRectMake(0, 0, 100, 100)
        UIGraphicsBeginImageContext(rect.size)
        //获取上下文
        let context = UIGraphicsGetCurrentContext()
        //填充颜色
        CGContextSetFillColorWithColor(context,color.CGColor)
        CGContextFillRect(context, rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
    /** 通过颜色生成圆形图片 */
//    class func getRoundImageWithColor(color:UIColor,radious:CGFloat) -> UIImage {
//        
//        
//        let rect = CGRectMake(0, 0, radious, radious)
//        //获取上下文
//        let context = UIGraphicsGetCurrentContext()
//        
//        CGContextAddEllipseInRect(context, rect)
//        CGContextSetFillColorWithColor(context,color.CGColor)
//        CGContextSetLineWidth(context, 10)
//        
//        CGContextStrokePath(context)
//
//        let image = UIGraphicsGetImageFromCurrentImageContext()
//        UIGraphicsEndImageContext()
//        
//        return image
//    }
    /** 截图 */
    class func captureView(targetView target:UIView) ->UIImage{
        // 获取目标UIView的所在的区域
        let rect = target.frame
        // 开始绘图
        UIGraphicsBeginImageContext(rect.size)
        // 获取当前的绘图Context
        let context = UIGraphicsGetCurrentContext()
        // 调用CALayer的方法将当前控件绘制到绘图Context中
        target.layer.renderInContext(context!)
        // 获取该绘图Context中的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    
    func clipByScalingAspectToMinSize(targetSize:CGSize) ->UIImage {
        
        // 获取源图片的宽和高
        let imageSize = self.size;
        let width = imageSize.width;
        let height = imageSize.height;
        let targetWidth = targetSize.width;
        let targetHeight = targetSize.height;
        // 定义图片缩放后的宽度
        var scaledWidth = targetWidth;
        // 定义图片缩放后的高度
        var scaledHeight = targetHeight;
        var anchorPoint = CGPointZero;
        // 如果源图片的大小与缩放的目标大小不相等
        if (!CGSizeEqualToSize(imageSize, targetSize))
        {
            // 计算水平方向上的缩放因子
            let xFactor = targetWidth / width;
            // 计算垂直方向上的缩放因子
            let yFactor = targetHeight / height;
            let scaleFactor = xFactor > yFactor ? xFactor : yFactor
            scaledWidth  = width * scaleFactor;
            scaledHeight = height * scaleFactor;
            if (xFactor > yFactor)
            {
                anchorPoint.y = (targetHeight - scaledHeight) * 0.5;
            }
            else if (xFactor < yFactor)
            {
                anchorPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }
        // 开始绘图
        UIGraphicsBeginImageContext(targetSize);
        var anchorRect = CGRectZero;
        anchorRect.origin = anchorPoint;
        anchorRect.size.width  = scaledWidth;
        anchorRect.size.height = scaledHeight;
        self.drawInRect(anchorRect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return newImage
    }
}
//MARK: - UICOLOR
extension UIColor {
    
    class func colorWithHexString (hexColor:String,alapha:CGFloat?) -> UIColor {
        
        var cString:String = hexColor.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
        
        if (cString.hasPrefix("#")) {
            
            cString = (cString as NSString).substringFromIndex(1)
        } else if cString.hasPrefix("0X") {
            cString = (cString as NSString).substringFromIndex(2)
        }
        
        if (cString.characters.count != 6) {
            return UIColor.whiteColor()
        }
        
        let rString = (cString as NSString).substringToIndex(2)
        let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
        let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
        
        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        NSScanner(string: rString).scanHexInt(&r)
        NSScanner(string: gString).scanHexInt(&g)
        NSScanner(string: bString).scanHexInt(&b)
//        debugPrint("r,g,b",r,g,b)
        
        
        if alapha == nil {
            
            return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1)
        } else {
            return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alapha!)
        }
    }
    func makeColorLight(color:UIColor) ->UIColor {
        
        //获得RGB值描述
        let RGBValue = String.init(format: "%@", color)//[NSString stringWithFormat:@"%@",color];
        //将RGB值描述分隔成字符串
        let RGBArr = RGBValue.componentsSeparatedByString(" ")
        //获取红色值
        let r = Int(RGBArr[1])! * 255
        //获取绿色值
        let g = Int(RGBArr[2])! * 255 //[[RGBArr objectAtIndex:2] intValue] * 255
        //获取蓝色值
        let b = Int(RGBArr[3])! * 255//[[RGBArr objectAtIndex:3] intValue] * 255
        return UIColor.init(red: CGFloat(r)*0.9, green: CGFloat(g)*0.9, blue: CGFloat(b)*0.9, alpha: 1)
    }
}





//MARK: - NSDEVICE
extension UIDevice{
    
    class var deviceModel: DeviceModel {
        
        var systemInfo = utsname()
        uname(&systemInfo)
        
        let modelCode = withUnsafeMutablePointer(&systemInfo.machine) {
            
            ptr in String.fromCString(UnsafePointer<CChar>(ptr))
        }
        var modelMap : [ String : DeviceModel ] = [
            "i386" : .Simulator,
            "x86_64" : .Simulator,
            "iPod1,1" : .iPod1,
            "iPod2,1" : .iPod2,
            "iPod3,1" : .iPod3,
            "iPod4,1" : .iPod4,
            "iPod5,1" : .iPod5,
            "iPad2,1" : .iPad2,
            "iPad2,2" : .iPad2,
            "iPad2,3" : .iPad2,
            "iPad2,4" : .iPad2,
            "iPad2,5" : .iPadMini1,
            "iPad2,6" : .iPadMini1,
            "iPad2,7" : .iPadMini1,
            "iPhone3,1" : .iPhone4,
            "iPhone3,2" : .iPhone4,
            "iPhone3,3" : .iPhone4,
            "iPhone4,1" : .iPhone4S,
            "iPhone5,1" : .iPhone5,
            "iPhone5,2" : .iPhone5,
            "iPhone5,3" : .iPhone5C,
            "iPhone5,4" : .iPhone5C,
            "iPad3,1" : .iPad3,
            "iPad3,2" : .iPad3,
            "iPad3,3" : .iPad3,
            "iPad3,4" : .iPad4,
            "iPad3,5" : .iPad4,
            "iPad3,6" : .iPad4,
            "iPhone6,1" : .iPhone5S,
            "iPhone6,2" : .iPhone5S,
            "iPad4,1" : .iPadAir1,
            "iPad4,2" : .iPadAir2,
            "iPad4,4" : .iPadMini2,
            "iPad4,5" : .iPadMini2,
            "iPad4,6" : .iPadMini2,
            "iPad4,7" : .iPadMini3,
            "iPad4,8" : .iPadMini3,
            "iPad4,9" : .iPadMini3,
            "iPhone7,1" : .iPhone6plus,
            "iPhone7,2" : .iPhone6,
            "iPhone8,1" : .iPhone6S,
            "iPhone8,2" : .iPhone6Splus
        ]
        if let model = modelMap[String.fromCString(modelCode!)!] {
            return model
        }
        return DeviceModel.Unrecognized
    }
}


//MARK: - NSDATA
extension NSData {
    
    func getNSDataWithArr(dict:Array<AnyObject>) ->NSData{
        let data = NSMutableData.init()
        let archiver = NSKeyedArchiver.init(forWritingWithMutableData: data)
        archiver.encodeObject(dict)
        archiver.finishEncoding()
        return data
    }
}
//MARK
//MARK: - NSOBJECT
extension NSObject {
    
//    func showAlertView(info:String,target:AnyObject) {
//        let alertVC = UIAlertController.init(title: "提示", message: info, preferredStyle: UIAlertControllerStyle.Alert)
//        let cancel = UIAlertAction.init(title: "我知道了", style: UIAlertActionStyle.Cancel) { (did) in
//            target.dismissViewControllerAnimated(true, completion: nil)
//        }
//        alertVC.addAction(cancel)
//        
//        target.presentViewController(alertVC, animated: true, completion: nil)
//    }
//    
//    func showAlertView(info:String,target:AnyObject,sure:(()->Void)?) {
//        
//        let alertVC = UIAlertController.init(title: "提示", message: info, preferredStyle: UIAlertControllerStyle.Alert)
//        let cancel = UIAlertAction.init(title: "否", style: UIAlertActionStyle.Cancel) { (cancel) in
//            target.dismissViewControllerAnimated(true, completion: nil)
//        }
//        let ok = UIAlertAction.init(title: "是", style: UIAlertActionStyle.Default) { (ok) in
//            if sure != nil {
//               sure!()
//            }
//        }
//        alertVC.addAction(cancel)
//        alertVC.addAction(ok)
//        target.presentViewController(alertVC, animated: true, completion: nil)
//    }
    
    func getUnixDateFormString(dateStr:String) -> String{
        let dateString = dateStr
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy.MM"
        let date = formatter.dateFromString(dateString)
        let xx = Int64((date?.timeIntervalSince1970)!)
        let str = String.init(format: "%d", xx)
        debugPrint("unix:--",str)
        return str
    }
    
    func getNowDateFormUnix() ->String{
        let data = NSDate()
        let dateFor = NSDateFormatter()
        dateFor.dateFormat = "yyyy年MM月dd日 HH:mm"
        let str = dateFor.stringFromDate(data)
        return str
    }
    
    //扩展 uidevice 设备详细型号 4s,6p
    
    public enum DeviceModel : String {
        case Simulator = "Simulator/Sandbox",
        iPod1 = "iPod 1", iPod2 = "iPod 2",
        iPod3 = "iPod 3", iPod4 = "iPod 4",
        iPod5 = "iPod 5",
        
        iPad2 = "iPad 2",iPad3 = "iPad 3",iPad4 = "iPad 4",
        
        iPhone4 = "iPhone 4", iPhone4S = "iPhone 4S",
        iPhone5 = "iPhone 5", iPhone5S = "iPhone 5S", iPhone5C = "iPhone 5C",
        
        iPadMini1 = "iPad Mini 1", iPadMini2 = "iPad Mini 2", iPadMini3 = "iPad Mini 3",
        
        iPadAir1 = "iPad Air 1", iPadAir2 = "iPad Air 2",
        iPhone6 = "iPhone 6", iPhone6plus = "iPhone 6 Plus",
        
        iPhone6S = "iPhone 6S", iPhone6Splus = "iPhone 6S Plus",
        Unrecognized = "?unrecognized?"
    }
    
    func getPicFromScreenView(view:UIView) -> UIImage{
        
        
        UIGraphicsBeginImageContext(view.frame.size)
        let context = UIGraphicsGetCurrentContext()
        
        CGContextSaveGState(context);
        UIRectClip(view.frame)
        
        view.layer.renderInContext(context!)
        let theImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        
        return  theImage
    }
    
    func getArrFormDictArrFilterKey(key:String,arrDict:Array<NSDictionary>) ->Array<String>{
        
        var arrStr = [String]()
        for item in arrDict {
            let str:String = (item[key] ?? LDNull) as! String
            arrStr.append(str)
        }
        return arrStr
    }
    
}
//MARK: - STRING
extension String {
    
    //获得自定义行距
    func getHeightFormAttr(lineSpace:CGFloat,title:String,size:CGSize,font:UIFont) ->CGFloat{
        
        let attr = getAttrFormString(lineH: lineSpace, text: title, font: font)
        
        let height = attr.boundingRectWithSize(size, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
        
        return height.size.height
    }
    //获得行间距富文本
    func getAttrFormString(lineH lineH:CGFloat,text:String,font:UIFont) ->NSMutableAttributedString {
        
        let paragrapStyle = NSMutableParagraphStyle()
        paragrapStyle.lineSpacing = lineH
        paragrapStyle.alignment = NSTextAlignment.Left
//        paragrapStyle.lineSpacing = 
        paragrapStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping
        
        let attr = NSMutableAttributedString.init(string: text)
        attr.addAttributes([NSParagraphStyleAttributeName:paragrapStyle,NSFontAttributeName:font], range: NSMakeRange(0, attr.length))
        return attr
    }
    //
    static func CountOfWordFromString(str:String) ->Int{
        
        let strText = NSString.init(string: str)
        return strText.length
    }
}
//MARK: - UITableViewCell
extension UITableViewCell {

}
//MARK: - DICTIONARY
extension Dictionary {
    //获得json字符串
    func jsonString() ->String {
        let dict:Dictionary = self
        
        let data = try? NSJSONSerialization.dataWithJSONObject(dict as! AnyObject, options: NSJSONWritingOptions.PrettyPrinted)
        let jsonStr:String = String.init(data: data!, encoding: NSUTF8StringEncoding)!
        
        return jsonStr
    }
    //data->value
    func getNSDataWithArr(dict:Array<AnyObject>) ->NSData{
        let data = NSMutableData.init()
        let archiver = NSKeyedArchiver.init(forWritingWithMutableData: data)
        archiver.encodeObject(dict)
        archiver.finishEncoding()
        return data
    }
    
    func getNSDataWithDict(dict:Dictionary<String,AnyObject>) ->NSData{
        let data = NSMutableData.init()
        let archiver = NSKeyedArchiver.init(forWritingWithMutableData: data)
        archiver.encodeObject(dict)
        archiver.finishEncoding()
        return data
    }
    //得到tag的title数组
//    func getTitleArrFromDictArr(key:String,dict:NSDictionary) -> Array<String> {
//        
//        let highlightsDict = dict[key] as? Array<NSDictionary>
//        var highlightsarr = [String]()
//        
//        for item in highlightsDict! {
//            highlightsarr.append(item["tag"] as! String)
//        }
//        return highlightsarr
//    }
}








